<?php
namespace app\common\logic;
use app\common\model\SpecGoodsPrice;
use app\common\model\Cart;
use app\common\model\Goods;
use app\common\model\Users;
use app\common\util\TpshopException;
use think\Model;
use think\facade\Db;
/**
 * 购物车 逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class CartLogic
{
    protected $goods;//商品模型
    protected $specGoodsPrice;//商品规格模型
    protected $goodsBuyNum;//购买的商品数量
    protected $user_id = 0;//user_id

    public function __construct($data=[])
    {
        if(isset($data['user_id'])){
            $this->setUserId($data['user_id']);
        }
        if(isset($data['goods_id'])){
            $this->setGoodsModel($data['goods_id']);
        }
        if(isset($data['item_id'])){
            $this->setSpecGoodsPriceModel($data['item_id']);
        }

        if(isset($data['goods_num'])){
            $this->setGoodsBuyNum($data['goods_num']);
        }
    }

    /**
     * 设置用户ID
     * @param $user_id
     */
    public function setUserId($user_id)
    {
        $this->user_id = $user_id;
    }

    /**
     * 包含一个商品模型
     * @param $goods_id
     */
    public function setGoodsModel($goods_id)
    {
        if($goods_id > 0){
//            $goodsModel = new Goods();
//            $this->goods = $goodsModel::get($goods_id);
            $goods = Db::name('goods')->where('goods_id',$goods_id)->find();
            logic('GoodsLogic')->getGoodsSeckill($goods);
            $this->goods = $goods;
        }
    }
    /**
     * 包含一个商品规格模型
     * @param $item_id
     */
    public function setSpecGoodsPriceModel($item_id)
    {
        if($item_id > 0){
            $this->specGoodsPrice = Db::name('spec_goods_price')->where('item_id',$item_id)->find();
            //替换为规格中的库存
            $this->goods['store_count'] = $this->specGoodsPrice['store_count'];
        }
    }

    /**
     * 设置购买的商品数量
     * @param $goodsBuyNum
     */
    public function setGoodsBuyNum($goodsBuyNum)
    {
        $this->goodsBuyNum = $goodsBuyNum;
    }

    /**
     * 立即购买
     * @return mixed
     * @throws TpshopException
     */
    public function buyNow(){
        $rs = $this->getValidate(2);
        if($rs['status']!=1){
            return $rs;
        }

        $buyGoods = [
            'user_id'=>$this->user_id,
            'sid' => $this->goods['sid'],
            'goods_id'=>$this->goods['goods_id'],
            'goods_name'=>$this->goods['goods_name'],
            'goods_num' => $this->goodsBuyNum, // 购买数量
            'spec_key_name'=>$this->specGoodsPrice['key_name']?$this->specGoodsPrice['key_name']:'',
            'spec_goods_id'=>$this->specGoodsPrice['item_id']?$this->specGoodsPrice['item_id']:'',
            'supplier_uid' => $this->goods['sid'],
            'cat_id' => $this->goods['cat_id'],
            'goods_nper'=>$this->goods['goods_nper'],
            'goods_sn'=>$this->goods['goods_sn'],
            'leixing_id'=>$this->goods['leixing_id'],
            'taozhuang_ids' => $this->goods['taozhuang_ids'],
            'level_limit' => $this->goods['level_limit'],
            'cat_id_1' => $this->goods['cat_id_1'],
            'cat_id_2' => $this->goods['cat_id_2'],
            'cat_id_3' => $this->goods['cat_id_3'],
            'is_seckill' => $this->goods['is_seckill'],
        ];
        $pp_youhui_bili = tpCache('basic.pp_youhui_bili');
        //动态价格数组
        $pricefilter  =  logic('GoodsLogic')->getFilterAttr();
        //转换价格
        if($this->specGoodsPrice){
            $spec[0] = $this->specGoodsPrice;
            logic('GoodsLogic')->getPriceNew($spec,$this->user_id);
            $this->specGoodsPrice = $spec[0];
            foreach ($pricefilter as $fk => $fv) {
                $buyGoods[$fv] = $this->specGoodsPrice[$fv];
            }
            if($buyGoods['leixing_id']==1){
                $buyGoods['youhui'] = bcmul($this->specGoodsPrice['shop_price'],$pp_youhui_bili/100,2);
            }
        }else{
            $goods[0] = $this->goods->toArray();
            logic('GoodsLogic')->getPrice($goods,$this->user_id);
            foreach ($pricefilter as $fk => $fv) {
                $buyGoods[$fv] = $goods[0][$fv];
            }
            if($buyGoods['leixing_id']==1){
                $buyGoods['youhui'] = bcmul($buyGoods['shop_price'],$pp_youhui_bili/100,2);
            }
        }
        $cartList[] = $buyGoods;
        //按供货商分组
        $cartList = $this->getSupplier($cartList);
        return $cartList;
    }
    public function buyPreview(){
        $rs = $this->getValidate(2);
        if($rs['status']!=1){
            return $rs;
        }

        $buyGoods = [
            'user_id'=>$this->user_id,
            'sid' => $this->goods['sid'],
            'goods_id'=>$this->goods['goods_id'],
            'goods_name'=>$this->goods['goods_name'],
            'goods_num' => $this->goodsBuyNum, // 购买数量
            'spec_key_name'=>$this->specGoodsPrice['key_name']?$this->specGoodsPrice['key_name']:'',
            'spec_goods_id'=>$this->specGoodsPrice['item_id']?$this->specGoodsPrice['item_id']:'',
            'supplier_uid' => $this->goods['sid'],
            'cat_id' => $this->goods['cat_id'],
            'goods_nper'=>$this->goods['goods_nper'],
            'goods_sn'=>$this->goods['goods_sn'],
            'leixing_id'=>$this->goods['leixing_id'],
            'original_img' => $this->goods['original_img'],
            'cat_id_1' => $this->goods['cat_id_1'],
            'cat_id_2' => $this->goods['cat_id_2'],
            'cat_id_3' => $this->goods['cat_id_3'],
            'is_seckill' => $this->goods['is_seckill'],
        ];
        //动态价格数组
        $pricefilter  =  logic('GoodsLogic')->getFilterAttr();
        //转换价格
        if($this->specGoodsPrice){
            $spec[0] = $this->specGoodsPrice;
            logic('GoodsLogic')->getPriceNew($spec,$this->user_id);
            foreach ($pricefilter as $fk => $fv) {
                $buyGoods[$fv] = $spec[0][$fv];
            }
        }else{
            $goods[0] = $this->goods->toArray();
            logic('GoodsLogic')->getPriceNew($goods,$this->user_id);
            foreach ($pricefilter as $fk => $fv) {
                $buyGoods[$fv] = $goods[0][$fv];
            }
        }
        //dump($buyGoods);exit;
        $cartList[] = $buyGoods;
        //按供货商分组
        $cartList = $this->getSupplier($cartList);
        return $cartList;
    }

    /**
     * 按供货商分组
     */
    public function getSupplier($goods){
        $list = [];
        foreach($goods as $k=>$v){
            $sid =$v['sid'];
            $supplier = Db::name('suppliers')->where('id',$sid)->find();
            if(empty($supplier)){
                $supplier = [
                    'id' => 0,
                    'name' => tpCache('basic.store_name'),
                    'logo' => tpCache('basic.store_log')
                ];
            }
            $list[$sid]['s_name'] = $supplier['name']??"官方店铺";
            $list[$sid]['goods'][]= $v;
            $list[$sid]['business']= $supplier;
            $list[$sid]['sid']= $sid;
        }
        return $list;
    }

    /**
     * 购买判断
     */
    public function getValidate($type){
        if(empty($this->goods)){
            return ['status'=>-3,'msg'=>'购买商品不存在'];
        }

        if($this->goods['is_on_sale']==0){
            return ['status'=>-1,'msg'=>'商品已下架'];
        }


        $rs = $this->qitaValidate($this->goods,$this->goodsBuyNum,$type);
        if(!$rs['status']){
            return $rs;
        }

        if(empty($this->specGoodsPrice) && $this->goods['spec_goods_id']>0){
            return array('status' => -1, 'msg' => '必须传递商品规格', 'result' => '');
        }
        //如果该商品没有存在购物车
        if($this->goodsBuyNum > $this->goods['store_count']){
            return array('status' => -4, 'msg' => '商品库存不足，剩余'.$this->goods['store_count'], 'result' => '');
        }


        return ['status'=>1];
    }

    //判断购买数量和时间 $type 1 购物车 2立即购买 3下订单
    public function qitaValidate($goods,$mainum,$type){
        //限购
        if($mainum<$goods['qsnum']){
            return ['status'=>0,'msg'=>'最低'.$goods['qsnum'].'件起售'];
        }

        //每人最多买几件
        $maxnum = $goods['xgnum'];
        $buynum = 0;
        //已经购买，下单也算
        $sum = Db::name('OrderGoods')->where(['user_id'=>$this->user_id,'goods_id'=>$goods['goods_id'],'order_status'=>['neq',6]])->sum('goods_num');
        if($sum){
            $buynum += $sum;
        }
        //剩余可买
        $sy = $maxnum-$buynum;
        if($sy<=0){
            return ['status'=>0,'msg'=>$goods['goods_name'].'最多购买'.$maxnum.'件，您已经购买达到上限'];
        }

        //判断品牌区PV
        if($goods['leixing_id']==1 && $type<3) {
            $user = Db::name('Users')->where(['user_id' => $this->user_id])->find();
            if($user['htstatus']!=1){
                if ($user['level'] > 5) {
//                    return ['status' => 0, 'msg' => '您已经成为VIP，请不要重复购买'];
                }

                $maipv = $goods['pv'] * $mainum;
                $ljpv = tpCache('basic.vip_pv');
                $sypv = $ljpv-$user['total_pv1'];//有可能先下单了
                if($sypv>0){
                    if ($maipv > $sypv) {
                        return ['status' => 0, 'msg' => '您购买的产品已超出额度'];
                    }
                }

                //判断购物车里面
                $allgoods = Db::name('goods')->column('leixing_id,pv','goods_id');
                $carts = Db::name('cart')->where(['user_id'=>$this->user_id])->select();
                if($carts){
                    $addpv = $maipv;
                    foreach($carts as $cval){
                        $gid = $cval['goods_id'];
                        if($allgoods[$gid]['leixing_id']!=1){
                            return ['status' => 0, 'msg' => '不同专区的商品，不同同时加入购物车'];
                        }
                        $addpv+=($allgoods[$gid]['pv']*$cval['goods_num']);
                    }

                    if ($addpv > $ljpv) {
                        return ['status' => 0, 'msg' => '您购买的产品已超出额度'];
                    }
                }
            }
        }

        //加入购物车的需要另算
        if($type==1){
            $c_sum = Db::name('cart')->where(['user_id'=>$this->user_id,'goods_id'=>$goods['goods_id']])->sum('goods_num');
            if($c_sum>0){
                if($c_sum>=$sy){
                    return ['status'=>0,'msg'=>$goods['goods_name'].'最多购买'.$maxnum.'件，您的购物车不能再添加更多数量'];
                }else{
                    $sy1 = $sy-$c_sum;
                    if($mainum>$sy1){
                        return ['status'=>0,'msg'=>$goods['goods_name'].'最多购买'.$maxnum.'件，您的购物车还能再添加'.$sy1.'件'];
                    }
                }
            }else{
                if($mainum>$sy){
                    return ['status'=>0,'msg'=>$goods['goods_name'].'最多购买'.$maxnum.'件，购物车只能再加'.$sy.'件'];
                }
            }

        }else{
            //立即购买
            if($mainum>$sy){
                return ['status'=>0,'msg'=>$goods['goods_name'].'最多购买'.$maxnum.'件，您还能再买'.$sy.'件'];
            }
        }

        //判断产品指定会员
//        if($goods['zduser']!=''){
//            $buy = explode(",",$goods['zduser_str']);
//            if(!in_array($this->user_id,$buy)){
//                return ['status'=>0,'msg'=>'产品信息有误'];
//            }
//        }

        return ['status'=>1];
    }

    /**
     * modify ：addCart
     * @return array
     */
    public function addGoodsToCart()
    {
        $rs=$this->getValidate(1);
        if($rs['status']!=1){
            return $rs;
        }

        $userCartCount = Db::name('cart')->where(['user_id'=>$this->user_id])->count();//获取用户购物车的商品有多少种
        if ($userCartCount >= 20) {
            return array('status' => -9, 'msg' => '购物车最多只能放20种商品', 'result' => '');
        }

        //普通产品
        $result = $this->addNormalCart();

        $result['result'] = $UserCartGoodsNum = $this->getUserCartGoodsNum(); // 查找购物车数量
        setcookie('cn', $UserCartGoodsNum, null, '/');
        return $result;
    }


    /**
     * 购物车添加普通商品
     * @return array
     */
    private function addNormalCart(){

        $store_count =  $this->goods['store_count'];
        $item_id = ($this->specGoodsPrice['item_id'] ?$this->specGoodsPrice['item_id']: '0');

        // 查询购物车是否已经存在这商品
        $userCartGoods = Db::name('cart')
            ->where('user_id',$this->user_id)
            ->where('goods_id',$this->goods['goods_id'])
            ->where('spec_goods_id',$item_id)
            ->find();
        // 如果该商品已经存在购物车
        if ($userCartGoods) {
            $userWantGoodsNum = $this->goodsBuyNum + $userCartGoods['goods_num'];//本次要购买的数量加上购物车的本身存在的数量

            if($userWantGoodsNum > 200){
                $userWantGoodsNum = 200;
            }
            if($userWantGoodsNum > $store_count){
                return array('status' => -4, 'msg' => '商品库存不足，剩余'.$store_count.',当前购物车已有'.$userCartGoods['goods_num'].'件', 'result' => '');
            }
            $cartResult = $userCartGoods->save(['goods_num' => $userWantGoodsNum]);
        }else{
            //不同类型的产品不能加入购物车
            $goods_ids = Db::name('cart')->where(['user_id'=>$this->user_id])->column('goods_id');
            if($goods_ids){
                $where = [];
                $where[] = ['goods_id','in',$goods_ids];
                $where[] = ['leixing_id','<>',$this->goods['leixing_id']];
                $no = Db::name('goods')->where($where)->find();
                if($no){
                    return ['status'=>0,'msg'=>'不同类型的产品不能同时加入购物车'];
                }
            }

            $cartAddData = array(
                'user_id' => $this->user_id,   // 用户id
                'sid' => $this->goods['sid'],   // 商品id
                'goods_id' => $this->goods['goods_id'],   // 商品id
//                'goods_name' => $this->goods['goods_name'],   // 商品名称
                'goods_num' => $this->goodsBuyNum, // 购买数量
                'add_time' => time(), // 加入购物车时间
                'spec_goods_id'=>$item_id,
            );
            $cartResult = Db::name('cart')->insertGetId($cartAddData);
        }
        if($cartResult !== false){
            return array('status' => 1, 'msg' => '成功加入购物车');
        }else{
            return array('status' => -1, 'msg' => '加入购物车失败');
        }
    }

    /**
     * 获取用户购物车商品总数
     * @return float|int
     */
    public function getUserCartGoodsNum()
    {
        $goods_num = Db::name('cart')->where(['user_id' => $this->user_id])->sum('goods_num');

        return empty($goods_num) ? 0 : $goods_num;
    }

    /**
     * @param int $selected|是否被用户勾选中的 0 为全部 1为选中  一般没有查询不选中的商品情况
     * 获取用户的购物车列表
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCartList($selected = 0){
        // 如果用户已经登录则按照用户id查询
        $cartWhere['user_id'] = $this->user_id;

        if($selected != 0){
            $cartWhere['selected'] = 1;
        }
        // 获取购物车商品
        $cartList = Db::name('cart')->where($cartWhere)->field('id,goods_id,spec_goods_id,goods_num,selected')->select()->toArray();
        if($cartList){
            //动态价格数组
            $pricefilter  =  logic('GoodsLogic')->getFilterAttr();

            //商品ids
            $goods_id = array();$spec_id = [];
            foreach($cartList as $val){
                $goods_id[] = $val['goods_id'];
                if($val['spec_goods_id']) $spec_id[] = $val['spec_goods_id'];
            }
            $goods = Db::name('Goods')->whereIn('goods_id',$goods_id)->column('goods_id,sid,level_limit,original_img,goods_name,is_on_sale,taozhuang_ids,leixing_id,'.implode(',',$pricefilter).',xgnum,qsnum,goods_sn,cat_id_1,cat_id_2,cat_id_3','goods_id');
            logic('GoodsLogic')->getPriceNew($goods, $this->user_id);
            //过滤掉无效的购物车商品
            $i=0;$leixing_id=0;
            foreach($cartList as $cartKey=>$cart){
                //商品不存在或者已经下架，或者规格不在
                if(empty($goods[$cart['goods_id']]) || $goods[$cart['goods_id']]['is_on_sale'] != 1 || $cart['goods_num'] == 0){
                    Db::name('Cart')->delete($cart['id']);
                    unset($cartList[$cartKey]);
                    continue;
                }
                $rs = $this->qitaValidate($goods[$cart['goods_id']],$cart['goods_num'],3);
                if(!$rs['status']){
                    return $rs;
                }
                if($i==0){
                    $leixing_id = $goods[$cart['goods_id']]['leixing_id'];
                }elseif($leixing_id!=$goods[$cart['goods_id']]['leixing_id']){
                    return ['status'=>0,'msg'=>'不同专区的产品不能同时购买，请清空购物车重新下单'];
                }

                $i++;
            }
            if($cartList){
                //获取价格和规格
                if($spec_id){
                    $spec = Db::name('SpecGoodsPrice')->whereIn('item_id',$spec_id)->column('item_id,goods_sn,key_name,'.implode(',',$pricefilter),'item_id');
                    logic('GoodsLogic')->getPrice($spec, $this->user_id);
                }
                $pp_youhui_bili = tpCache('basic.pp_youhui_bili');
                foreach($cartList as $key=>$val){
                    $gid = $val['goods_id'];
                    $cartList[$key]['spec_key_name'] = '';
                    $cartList[$key]['goods_name'] = $goods[$gid]['goods_name'];
                    $cartList[$key]['supplier_uid'] = $goods[$gid]['sid'];
                    $cartList[$key]['sid'] = $goods[$gid]['sid'];
                    $cartList[$key]['goods_sn'] = $goods[$gid]['goods_sn'];
                    $cartList[$key]['leixing_id'] = $goods[$gid]['leixing_id'];
                    $cartList[$key]['taozhuang_ids'] = $goods[$gid]['taozhuang_ids'];
                    $cartList[$key]['level_limit'] = $goods[$gid]['level_limit'];
                    $cartList[$key]['original_img'] = $goods[$gid]['original_img'];
                    $cartList[$key]['cat_id_1'] = $goods[$gid]['cat_id_1'];
                    $cartList[$key]['cat_id_2'] = $goods[$gid]['cat_id_2'];
                    $cartList[$key]['cat_id_3'] = $goods[$gid]['cat_id_3'];
                    $cartList[$key]['is_seckill'] = $goods[$gid]['is_seckill'];;
                    $cartList[$key]['checked'] = false;
                    if($val['spec_goods_id']){
                        //规格值赋值
                        $cartList[$key]['spec_key_name'] = $spec[$val['spec_goods_id']]['key_name'];
                        //规格价格替换产品价格
                        foreach($pricefilter as $fk=>$fv){
                            $cartList[$key][$fv] = $spec[$val['spec_goods_id']][$fv];
                        }
                        $cartList[$key]['goods_sn'] =$spec[$val['spec_goods_id']]['goods_sn'];
                    }else{//商品价格
                        foreach ($pricefilter as $fk => $fv) {
                            $cartList[$key][$fv] = $goods[$gid][$fv];
                        }
                    }

                }
                //保存价格
                $Cart = new cart();
                $Cart->saveAll($cartList);
                $cartGoodsTotalNum = array_sum(array_map(function($val){return $val['goods_num'];}, $cartList));//购物车购买的商品总数
                setcookie('cn', $cartGoodsTotalNum, null, '/');
                $cartList = $this->getSupplier($cartList);
            }
        }
        return $cartList;
    }

    /**
     *  modify ：cart_count
     *  获取用户购物车欲购买的商品有多少种
     * @return int|string
     */
    public function getUserCartOrderCount(){
        $count = Db::name('Cart')->where(['user_id' => $this->user_id , 'selected' => 1])->count();
        return $count;
    }

    /**
     * 更改购物车的商品数量
     * @param $cart_id|购物车id
     * @param $goods_num|商品数量
     * @return array
     */
    public function changeNum($cart_id, $goods_num){
        $cart = Db::name('cart')->where('id',$cart_id)->find();
        if($goods_num > 200){
            $goods_num = 200;
        }
        if($goods_num > $cart['store_count']){
            return ['status' => 0, 'msg' => '商品数量不能大于'.$cart->store_count, 'result' => ['limit_num'=>$cart->store_count]];
        }

        Db::name('cart')->where('id',$cart_id)->update(['goods_num'=>$goods_num]);
        return ['status' => 1, 'msg' => '修改商品数量成功', 'result' => ''];
    }
    /**
     * 删除购物车商品
     * @param array $cart_ids
     * @return int
     * @throws \think\Exception
     */
    public function delete($cart_ids = array()){

        $cartWhere['user_id'] = $this->user_id;

        $delete = Db::name('cart')->where($cartWhere)->where('id','IN',$cart_ids)->delete();
        return $delete;
    }

    /**
     *  更新购物车，并返回计算结果
     * @param array $cart
     * @return array
     */
    public function AsyncUpdateCart($cart = [])
    {
        $cartSelectedId = $cartNoSelectedId = [];
        if (empty($cart)) {
            return ['status' => 0, 'msg' => '购物车没商品'];
        }
        foreach ($cart as $key => $val) {
            if ($cart[$key]['selected'] == 1) {
                $cartSelectedId[] = $cart[$key]['id'];
            } else {
                $cartNoSelectedId[] = $cart[$key]['id'];
            }
        }
        $Cart = Db::name('cart');
        $cartWhere['user_id'] = $this->user_id;

        if (!empty($cartNoSelectedId)) {
            $Cart->where('id', 'IN', $cartNoSelectedId)->where($cartWhere)->update(['selected' => 0]);
        }
        if (empty($cartSelectedId)) {
            return ['status' => 0, 'msg' => '购物车没选中商品'];
        }
        $cartList = $Cart->where('id', 'IN', $cartSelectedId)->where($cartWhere)->select();
        foreach($cartList as $cartKey=>$cartVal){
            if($cartList[$cartKey]['selected'] == 0){
                $Cart->where('id', 'IN', $cartSelectedId)->where($cartWhere)->update(['selected' => 1]);
                break;
            }
        }
        $list[]['goods'] = $cartList;

        $cartPriceInfo = $this->getCartPriceInfo($list);
        $cartPriceInfo['cartList'] = $list;
        return ['status' => 1, 'msg' => '计算成功', 'result' => $cartPriceInfo];
    }

    /**
     * 获取购物车的价格详情
     * @param $cartList|购物车列表
     * @return array
     */
    public function getCartPriceInfo(&$cartList = null,$coupon_ids=[],$use_score=0,$cuxiao_ids=[]){
        $goods_num = 0;
        $total_shop_price=0;
        $total_youhui = 0;
        $select_prid = [];
        $score_total = Db::name('wallet')->where('user_id',$this->user_id)->value('score');
        $score_money_total = 0;//积分抵扣订单金额
        $score_to_money = tpCache('shop.score_to_money')?:0;//每积分可抵扣多少元
        $score_max_bili = tpCache('shop.score_max_bili')?:0;//平台设置的积分抵扣比例
        if($cartList){
            foreach ($cartList as $cartKey => $val) {
                $proids = [];
                $cids = [];
                $total_num = 0;
                foreach($val['goods'] as $cartItem){
                    if(empty($cartList[$cartKey]['total_shop_price'])){
                        $cartList[$cartKey]['total_shop_price'] = 0;
                    }
                    $cartList[$cartKey]['total_shop_price'] += $cartItem['shop_price']*$cartItem['goods_num'];
                    //全部总价
                    $total_shop_price += $cartItem['shop_price']*$cartItem['goods_num'];
                    $goods_num += $cartItem['goods_num'];
                    $total_num += $cartItem['goods_num'];
                    $proids[] = $cartItem['goods_id'];
                    $cids[] = $cartItem['cat_id_1'];
                    $cids[] = $cartItem['cat_id_2'];
                    $cids[] = $cartItem['cat_id_3'];

                    //计算积分抵扣
                    $goods = Db::name('goods')->where('goods_id',$cartItem['goods_id'])->find();
                    if(empty($goods['no_use_score'])){
                        //可使用积分抵扣的订单金额
                        $score_money_total = bcadd($score_money_total,bcmul($cartItem['shop_price'],$cartItem['goods_num'],2),2);
                    }

                }
                //积分可抵扣的金额
                $score_dec_money = bcmul($score_max_bili/100,$score_money_total,2);
                if($score_total<$score_dec_money){
                    $score_dec_money = $score_total;
                }
                $score_dec_money = min([$score_dec_money,$score_money_total]);
                //需要扣除的积分
                if($score_to_money>0){
                    $dec_score = bcdiv($score_dec_money,$score_to_money,2);
                }else{
                    $dec_score = 0;
                }

                $cartList[$cartKey]['score_money'] = $score_dec_money;//积分抵扣金额
                $cartList[$cartKey]['pay_score'] = $dec_score;//需要扣除的积分数量
                $cartList[$cartKey]['use_score'] = $use_score;//是否使用积分抵扣
                $score_total = bcsub($score_total,$dec_score,2);//总积分减掉已抵扣部分的积分
                //计算优惠券
                $coupon_money = 0;
                $user_id = $this->user_id;
                $sid_couponrids = [];
                if($coupon_ids){
                    foreach($coupon_ids as $sid=>$coupon_arr){
                        if($sid!=$cartKey){
                            break;
                        }
                        foreach($coupon_arr as $couponrid){
                            if(in_array($couponrid,$select_prid)){
                                continue;
                            }
                            $prolist = Db::name('goods')->where('goods_id','in',$proids)->select()->toArray();
                            $totalprice = $cartList[$sid]['total_shop_price'];
                            $couponrecord = Db::name('coupon_record')->where('user_id',$user_id)->where('id',$couponrid)->find();
                            if(!$couponrecord){
                                //return ['status'=>0,'msg'=>'该优惠券不存在'];
                                continue;
                            }elseif($couponrecord['status']!=0){
                                //return ['status'=>0,'msg'=>'该优惠券已使用过了'];
                                continue;
                            }elseif($couponrecord['starttime'] > time()){
                                //return ['status'=>0,'msg'=>'该优惠券尚未开始使用'];
                                continue;
                            }elseif($couponrecord['endtime'] < time()){
                                //return ['status'=>0,'msg'=>'该优惠券已过期'];
                                continue;
                            }elseif($couponrecord['minprice'] > $totalprice){
                                //return ['status'=>0,'msg'=>'该优惠券不符合条件'];
                                continue;
                            }
                            $couponinfo = Db::name('coupon')->where('id',$couponrecord['couponid'])->find();
                            if(empty($couponinfo)){
                                //return ['status'=>0,'msg'=>'该优惠券不存在或已作废'];
                                continue;
                            }
                            //0全场通用,1指定类目,2指定商品
                            if(!in_array($couponinfo['fwtype'],[0,1,2])){
                                //return ['status'=>0,'msg'=>'该优惠券超出可用范围'];
                                continue;
                            }

                            $usetj = explode(',',$couponinfo['usetj']);
                            if(!in_array('-1',$usetj) && !in_array($this->member['levelid'],$usetj) && (!in_array('0',$usetj) || $this->member['subscribe']!=1)){
                                //return ['status'=>0,'msg'=>'该优惠券不可用'];
                                continue;
                            }
                            if($couponinfo['fwtype']==2){//指定商品可用
                                $productids = explode(',',$couponinfo['productids']);
                                if(!array_intersect($proids,$productids)){
                                    //return ['status'=>0,'msg'=>'该优惠券指定商品可用'];
                                    continue;
                                }
                                $thistotalprice = 0;
                                foreach($val['goods'] as $suid=>$sval) {
                                    foreach ($sval['goods'] as $gval) {
                                        if (in_array($gval['goods_id'], $productids)) {
                                            $thistotalprice += $gval['sell_price'] * $gval['num'];
                                        }
                                    }
                                }
                                if($thistotalprice < $couponinfo['minprice']){
                                    //return ['status'=>0,'msg'=>'该优惠券指定商品未达到'.$couponinfo['minprice'].'元'];
                                    continue;
                                }
                                $couponrecord['money'] = min($thistotalprice,$couponrecord['money']);
                            }
                            if($couponinfo['fwtype']==1){//指定类目可用
                                $categoryids = explode(',',$couponinfo['categoryids']);
                                $clist = Db::name('shop_category')->where('pid','in',$categoryids)->select()->toArray();
                                foreach($clist as $kc=>$vc){
                                    $categoryids[] = $vc['id'];
                                    $cate2 = Db::name('shop_category')->where('pid',$vc['id'])->find();
                                    if($cate2) $categoryids[] = $cate2['id'];
                                }
                                if(!array_intersect($cids,$categoryids)){
                                    //return ['status'=>0,'msg'=>'该优惠券指定分类可用'];
                                    continue;
                                }
                                $thistotalprice = 0;
                                $thistotalprice = 0;
                                foreach($val['goods'] as $suid=>$sval) {
                                    foreach ($sval['goods'] as $gval) {
                                        if(array_intersect(explode(',',$gval['cid']),$categoryids)){
                                            $thistotalprice += $gval['sell_price'] * $gval['num'];
                                        }
                                    }
                                }
                                if($thistotalprice < $couponinfo['minprice']){
                                    //return ['status'=>0,'msg'=>'该优惠券指定分类未达到'.$couponinfo['minprice'].'元'];
                                    continue;
                                }
                                $couponrecord['money'] = min($thistotalprice,$couponrecord['money']);
                            }

                            if($couponrecord['type']==4){//运费抵扣券
                                $new_freight_price = 0;
                            }elseif($couponrecord['type']==2) {//折扣券
                                if ($couponinfo['fwtype'] == 1 || $couponinfo['fwtype'] == 2) {
                                    $coupon_money += $thistotalprice * (100 - $couponrecord['discount']) * 0.01;
                                } else {
                                    $coupon_money += $totalprice * (100 - $couponrecord['discount']) * 0.01;
                                }
                                if ($coupon_money > $totalprice) $coupon_money = $totalprice;
                            }else{
                                $coupon_money += $couponrecord['money'];
                                if($coupon_money > $totalprice) $coupon_money = $totalprice;
                            }
                            $select_prid[] = $couponrid;
                            $sid_couponrids[] = $couponrid;
                        }

                    }
                }

                $cartList[$cartKey]['coupon_money'] = $coupon_money;
                $cartList[$cartKey]['coupon_ids'] = $sid_couponrids;
                //总价-优惠券金额-积分抵扣金额
                //$cartList[$cartKey]['total_shop_price'] = bcsub($cartList[$cartKey]['total_shop_price'],$coupon_money,2);
                $total_shop_price = bcsub($total_shop_price,$coupon_money,2);
                if($use_score){
                    //$cartList[$cartKey]['total_shop_price'] = bcsub($cartList[$cartKey]['total_shop_price'],$score_dec_money,2);
                    $total_shop_price = bcsub($total_shop_price,$score_dec_money,2);
                }
                //促销活动
                $cuxiao_money = 0;
                if($cuxiao_ids){
                    foreach($cuxiao_ids as $sid=>$cuxiaoid){
                        if($sid!=$cartKey){
                            break;
                        }
                        $totalprice = $cartList[$sid]['total_shop_price'];
                        $cuxiaoinfo = Db::name('cuxiao')->where("sid=-1 or sid=".$sid)->where('id',$cuxiaoid)->find();
                        if(!$cuxiaoinfo){
                           // return $this->json(['status'=>0,'msg'=>'该促销活动不存在']);
                            continue;
                        }elseif($cuxiaoinfo['starttime'] > time()){
                            //return $this->json(['status'=>0,'msg'=>'该促销活动尚未开始']);
                            continue;
                        }elseif($cuxiaoinfo['endtime'] < time()){
                            //return $this->json(['status'=>0,'msg'=>'该促销活动已结束']);
                            continue;
                        }elseif($cuxiaoinfo['type']!=5 && $cuxiaoinfo['type']!=6 && $cuxiaoinfo['minprice'] > $totalprice){
                            //return $this->json(['status'=>0,'msg'=>'该促销活动不符合条件']);
                            continue;
                        }elseif(($cuxiaoinfo['type']==5 || $cuxiaoinfo['type']==6) && $cuxiaoinfo['minnum'] > $total_num){
                            //return $this->json(['status'=>0,'msg'=>'该促销活动不符合条件']);
                            continue;
                        }
                        $prolist = [];
                        if($cuxiaoinfo['fwtype']==0){
                            //所有商品可用
                            $prolist = $val['goods'];
                        }elseif($cuxiaoinfo['fwtype']==1){
                            //指定类目可用
                            $categoryids = explode(',',$cuxiaoinfo['categoryids']);
                            $clist = Db::name('goods_category')->where('pid','in',$categoryids)->select()->toArray();
                            foreach($clist as $kc=>$vc){
                                $categoryids[] = $vc['id'];
                                $cate2 = Db::name('goods_category')->where('pid',$vc['id'])->find();
                                $categoryids[] = $cate2['id'];
                            }
                            foreach($val['goods'] as $product){
                                if(in_array($product['cat_id_1'],$categoryids) || in_array($product['cat_id_2'],$categoryids) || in_array($product['cat_id_3'],$categoryids)){
                                    $prolist[] = $product;
                                }
                            }
                        }elseif($cuxiaoinfo['fwtype']==2){
                            //指定商品可用
                            $productids = explode(',',$cuxiaoinfo['productids']);
                            foreach($val['goods'] as $product){
                                if(in_array($product['goods_id'],$productids)){
                                    $prolist[] = $product;
                                }
                            }
                        }
                        $totalprice = 0;
                        $total_num = 0;
                        foreach($prolist as $pro){
                            $total_num += $pro['goods_num'];
                            $totalprice = bcadd($totalprice,bcmul($pro['shop_price'],$pro['goods_num'],2),2);
                        }
                        //dump($cuxiaoinfo);
                        if($cuxiaoinfo['type']==1){
                            //满额立减
                            if($totalprice>=$cuxiaoinfo['minprice']){
                                $manjian_money = $manjian_money + $cuxiaoinfo['money'];
                                $cuxiaomoney = $cuxiaoinfo['money'];
                            }
                        }elseif($cuxiaoinfo['type']==2){//满额赠送
                            if($totalprice>=$cuxiaoinfo['minprice']) {
                                $cuxiaomoney = 0;
                                $product = Db::name('goods')->where('id', $cuxiaoinfo['proid'])->find();
                                $guige = Db::name('spec_goods_price')->where('id', $cuxiaoinfo['ggid'])->find();
                                if (!$product){
                                    //return $this->json(['status' => 0, 'msg' => '赠送产品不存在']);
                                    continue;
                                }
                                if (!$guige) {
                                    //return $this->json(['status' => 0, 'msg' => '赠送产品规格不存在']);
                                    continue;
                                }
                                if ($guige['stock'] < 1) {
                                    //return $this->json(['status' => 0, 'msg' => '赠送产品库存不足']);
                                    continue;
                                }
                                $prolist[] = ['product' => $product, 'guige' => $guige, 'num' => 1, 'isSeckill' => 0, 'gtype' => 1];
                            }
                        }elseif($cuxiaoinfo['type']==3){//加价换购
                            if($totalprice>=$cuxiaoinfo['minprice']) {
                                $cuxiaomoney = $cuxiaoinfo['money'];
                                $product = Db::name('goods')->where('id', $cuxiaoinfo['proid'])->find();
                                $guige = Db::name('spec_goods_price')->where('id', $cuxiaoinfo['ggid'])->find();
                                if (!$product){
                                    //return $this->json(['status' => 0, 'msg' => '换购产品不存在']);
                                    continue;
                                }
                                if (!$guige){
                                    //return $this->json(['status' => 0, 'msg' => '换购产品规格不存在']);
                                    continue;
                                }
                                if ($guige['stock'] < 1) {
                                    //return $this->json(['status' => 0, 'msg' => '换购产品库存不足']);
                                    continue;
                                }
                                $prolist[] = ['product' => $product, 'guige' => $guige, 'num' => 1, 'isSeckill' => 0];
                            }
                        }elseif($cuxiaoinfo['type']==4){
                            //满额打折
                            if($totalprice>=$cuxiaoinfo['minprice']) {
                                $cuxiaomoney = $totalprice * (1 - $cuxiaoinfo['zhekou'] * 0.1);
                                $cuxiaomoney = round($cuxiaomoney, 2);
                                $manjian_money = $manjian_money + $cuxiaomoney;
                                $cuxiaomoney = $cuxiaomoney ;
                            }
                        }elseif($cuxiaoinfo['type']==5){
                            //满件打折
                            if($total_num>=$cuxiaoinfo['minnum']) {
                                $cuxiaomoney = $totalprice * (1 - $cuxiaoinfo['zhekou'] * 0.1);
                                $cuxiaomoney = round($cuxiaomoney, 2);
                                $manjian_money = $manjian_money + $cuxiaomoney;
                                $cuxiaomoney = $cuxiaomoney ;
                            }
                        }elseif($cuxiaoinfo['type']==6){
                            //满件立减
                            if($total_num>=$cuxiaoinfo['minnum']) {
                                $manjian_money = $manjian_money + $cuxiaoinfo['money'];
                                $cuxiaomoney = $cuxiaoinfo['money'] ;
                            }
                        }else{
                            $cuxiaomoney = 0;
                        }
                        //dump($cuxiaomoney);exit;
                        $cartList[$cartKey]['cuxiao_id'] = $cuxiaoid;
                        $cartList[$cartKey]['cuxiao_money'] = $cuxiaomoney;
                        $cartList[$cartKey]['cuxiaonameArr'][] = $cuxiaoinfo['name'];
                    }
                }else{
                    $cuxiaomoney = 0;
                }
                $total_shop_price = $total_shop_price - $cuxiaomoney;

            }
        }
        return compact('total_shop_price', 'goods_num','total_youhui');
    }

    /**
     * 清除用户购物车选中
     * @throws \think\Exception
     */
    public function clear()
    {
        Db::name('cart')->where(['user_id' => $this->user_id, 'selected' => 1])->delete();
    }
}